package conf

import (
	"github.com/go-ini/ini"
	"log"
	"time"
)

type App struct {
	JwtSecret        string
	PageSize         int
	PrefixUrl        string
	SysPackPath      string
	MasterDockerImagesPath string
	WorkerDockerImagesPath string
	MaxUploadSize    int64
}

var AppSetting = &App{}

type Log struct {
	LogSavePath string
	LogFileName string
	LogLevel    int
	LogType     string
}

var LogSetting = &Log{}

type Server struct {
	RunMode      string
	HttpPort     string
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

var ServerSetting = &Server{}

type Database struct {
	Type              string
	User              string
	Password          string
	Host              string
	Name              string
	EnableAutoMigrate bool
	EnableDebug       bool
}

var DatabaseSetting = &Database{}

type Harbor struct {
	UserName string
	Password string
	Host     string
}

var HarborSetting = &Harbor{}

type Redis struct {
	Host        string
	Password    string
	MaxIdle     int
	MaxActive   int
	IdleTimeout time.Duration
}

var RedisSetting = &Redis{}

var cfg *ini.File

// Setup initialize the configuration instance
func init() {
	var err error
	cfg, err = ini.Load("conf/app.ini")
	if err != nil {
		log.Fatalf("setting.Setup, fail to parse 'conf/app.ini': %v", err)
	}

	mapTo("app", AppSetting)
	mapTo("log", LogSetting)
	mapTo("server", ServerSetting)
	mapTo("database", DatabaseSetting)
	mapTo("harbor", HarborSetting)
	mapTo("redis", RedisSetting)

	AppSetting.MaxUploadSize = AppSetting.MaxUploadSize * 1024 * 1024 * 1024
	//file.MkDir(AppSetting.SysPackPath)
	//file.MkDir(AppSetting.DockerImagesPath)

	ServerSetting.ReadTimeout = ServerSetting.ReadTimeout * time.Second
	ServerSetting.WriteTimeout = ServerSetting.WriteTimeout * time.Second
	RedisSetting.IdleTimeout = RedisSetting.IdleTimeout * time.Second

}

// mapTo map section
func mapTo(section string, v interface{}) {
	err := cfg.Section(section).MapTo(v)
	if err != nil {
		log.Fatalf("Cfg.MapTo %s err: %v", section, err)
	}
}
